//app.js
// 判断是否登
App({
    //全局变量 图片url
    globalData: {
        userInfo: null,
        // url: 'http://vcjf888.natapp1.cc',
        url: 'https://m.vc-group.cn/wash-car-api',
        imageUrl: 'http://static.vc-group.cn/',
        user: null,
        hasUser: false
    },
    tempData:{},
    onLaunch: function() {
        this.cleanCache();
        console.log('app onLaunch')
        this.login();
    },
    login: function() {
        let that = this;
        wx.getSetting({
            success: setRes => {
                if (setRes.authSetting['scope.userInfo']) {
                    //认证标记
                    this.globalData.isAuthUserInfo = true;
                    wx.getUserInfo({
                        success: res => {

                            console.log("app.js 28 获取用户信息成功,设置用户",res);
                            that.globalData.userInfo = res.userInfo
                            // 检查 session_key 是否过期
                            wx.checkSession({
                                // session_key 有效(未过期)
                                success: function() {
                                    console.log("session_key 有效(未过期),获取缓存数据");
                                    that.doLogin();
                                    // // 获取缓存数据
                                    // that.globalData.user=wx.getStorageSync('user');
                                    // if (!that.globalData.user){
                                    //     console.log("本地缓存已被清空,重新登录");
                                    //     that.doLogin();
                                    //     return;
                                    // }
                                    // that.globalData.hasUser = true;
                                    // console.log(that.globalData.user);
                                    // //自动刷新缓存和重新登录
                                    // that.reLogin();
                                    // 由于 getUserInfo 是网络请求，可能会在 Page.onLoad 之后才返回
                                    // 所以此处加入 callback 以防止这种情况
                                    // if (that.userInfoReadyCallback) {
                                    //     console.log("do userInfo Ready Callback")
                                    //     that.userInfoReadyCallback(res.userInfo)
                                    // }
                                },
                                // session_key 过期
                                fail: function() {
                                    // session_key过期，重新登录
                                    console.log("app.js 48 ","session_key过期，重新登录")
                                    that.doLogin();
                                }
                            })
                        },
                        fail: function() {
                            //显示认证提示
                            that.showAuthUserInfo();
                        }
                    });
                } else {
                    //显示认证提示
                    that.showAuthUserInfo();
                }
            },
            fail: function () {
                //显示认证提示
                that.showAuthUserInfo();
            }
        })

    },
    doLogin: function() {
        var that = this;
        //客户端登录
        wx.login({
            success: function(res) {
                console.log("app.js 71 wx.login().success","客户端登录");
                if (res.code) {
                    that.doUserLogin(res.code);
                } else {
                    wx.clearStorageSync();
                    console.log('登录失败！' + res.errMsg)
                    wx.showModal({
                        title: '提示',
                        content: '登录失败！code为空.',
                        showCancel: false,
                    })
                }
            },
            fail:res=>{
                wx.showModal({
                    title: '提示',
                    content: '网络异常,登录失败!',
                    showCancel: false,
                })
            }
        });
    }, 
    onUnload: function () {
        // Do something when page close.
        console.log("page close")
        this.cleanCache(null);
    },
    //显示授权提示
    showAuthUserInfo() {
        //认证标记
        this.globalData.isAuthUserInfo = false;
        wx.showModal({
            title: '提示',
            content: '获取用户信息失败,请点击头像重新授权登录?',
            showCancel: false,
        })
    },
    setUserInfo(res){
        console.log('登录成功!');
        wx.setStorageSync('token', res.data.token);
        wx.setStorageSync('uuId', res.data.user.uuId);
        res.data.user.isBind = res.data.isBind
        wx.setStorageSync('isBind', res.data.isBind);
        this.globalData.user = res.data.user;
        wx.setStorageSync('user', res.data.user);
        this.globalData.hasUser = true;
    },
    //自动刷新缓存和重新登录
    reLogin(){
        let that = this;
        // return
        {
            //30分钟后自动重新登录,
            setInterval(() => {
                console.log("30分钟,自动重新登录");
                // 检查 session_key 是否过期
                wx.checkSession({
                    // session_key 有效(未过期)
                    success: function () {
                        // 刷新token
                        that.post("/refreshToken", {
                        }, res => {
                            console.log(res);
                            if (res.code == 0) {
                                that.setUserInfo(res);
                            } else {
                                that.cleanCache("自动刷新缓存失败,请手动重新登录");
                            }
                        })
                    },
                    fail: res => {
                        that.cleanCache();
                        that.doLogin()
                    }
                })
            }, 29 * 60 *3000);//
            // wx.setStorageSync('isLogin', true)
        }
    },
    doUserLogin: function(code) {
        wx.showLoading({
            title: '登陆中...',
        })
        var userInfo = this.globalData.userInfo;
        if(!userInfo){
            userInfo={};
        }
        let param = {
            code: code,
            nickname: userInfo.nickName ? userInfo.nickName : "",
            headPhoto: userInfo.avatarUrl ? userInfo.avatarUrl : ""
        };
        // console.log(param)
        let that = this;
        this.post('/login', param, function(res) {
            wx.hideLoading();
            if (res.code == 0) {
                console.log(res);
                that.setUserInfo(res);
                //自动刷新token
                that.reLogin();
                //登录成功后回调
                if (that.userInfoReadyCallback) {
                    console.log("登录成功后回调")
                    that.userInfoReadyCallback(that.globalData.userInfo)
                }
            } else { //登录失败
                console.log('登录失败!', res);
                wx.clearStorageSync();
                wx.showModal({
                    title: '登录失败!',
                    content: '服务器繁忙,请稍后再试.',
                    showCancel:false
                })
            }
        });
    },
    //点击浏览大图
    PI(nowImgUrl, imageUrls) {
        wx.previewImage({
            current: nowImgUrl, // 当前显示图片的http链接
            urls: imageUrls, // 需要预览的图片http链接列表
        })
    },
    //ajax函数get
    getDict(dictType, callback) {
        let url = '/dict/dict/findDictList';
        let data={
            type: dictType
        }
        this.getJson(url, data, callback);
    },
    getJson(url, data, callback) {
        let that= this;
        wx.request({
            url: that.globalData.url + url,
            data: data ? data : {},
            header: {
                'Content-Type': 'application/x-www-form-urlencoded',
                'token': wx.getStorageSync('token'),
                'loginId': wx.getStorageSync('uuId'),
            },
            method: 'GET',
            success(res) {
                console.log('getJson==>>',res)
                if ( res.data.code == -1 ) {
                    console.log("00000000000000")
                    that.cleanCache('登录已过期,请重新登录');
                    return;
                }
                if (typeof callback == 'function') {
                    callback(res.data);
                } 
            },
            fail(e) {
                wx.showModal({
                    title: '提示',
                    content: '网络请求失败',
                    showCancel: false
                })
                console.log(e);
                if (typeof callback == 'function') {
                    callback(e);
                }
            }
        })
    },
    // ajax函数POST
    post(url, data, callback) { 
     let that = this;
        wx.request({
            url: that.globalData.url + url,
            data: data ? data : {},
            header: {
                'Content-Type': 'application/x-www-form-urlencoded',
                'token': wx.getStorageSync('token'),
                'loginId': wx.getStorageSync('uuId'),
            },
            method: 'POST',
            success(res) {
                console.log('post==>>',res)
                if (res.data.code == -1) {
                    console.log("00000000000000")
                    that.cleanCache('登录已过期,请重新登录');
                    return;
                }
                if (typeof callback == 'function') {
                    callback(res.data);
                } 
            },
            fail(e) {
                wx.showModal({
                    title: '提示',
                    content: '网络请求失败',
                    showCancel: false
                })
                console.log(e);
                if (typeof callback == 'function') {
                    callback(e);
                }
            }
        })
    },
    /**清空缓存 */
    cleanCache(that) {
        console.log("------------cleanCache--------")
        wx.clearStorageSync();
        this.globalData.userInfo=null;
        this.globalData.user=null;
        this.globalData.hasUser= false;
        this.globalData.isBind= false;
        this.tempData = {};
        if (that && typeof that != 'string'){
            that.setData({
                userInfo: {},
                hasUserInfo: false,
                isBind: false,
            })
            return;
        }
        if (that){
            wx.showModal({
                title: '提示',
                content: that,
                showCancel: false
            })
        }
    }
    ,/*** 获取验证码*/
    doGetCode: function (phone,that) {
        let warn;
        if (!phone) {
            warn = "手机号码不能为空";
        } else if (phone.trim().length != 11 || !/^1[3|4|5|6|7|8|9]\d{9}$/.test(phone)) {
            warn = "手机号格式不正确";
        }
        if (warn) {
            wx.showModal({
                title: '提示',
                content: warn,
                showCancel: false
            })
            return;
        }
        that.setData({
            getCodeDisabled: true, //只要点击了按钮就让按钮禁用 （避免正常情况下多次触发定时器事件）
            getCodeColor: '#ccc',
        })
        let url = '/user/user/sendSms';
        this.getJson(url, {
            phone: phone
        }, res => {
            if (res.code == 0) {
                wx.showToast({
                    title: '发送成功',
                })
                wx.setStorageSync('phoneCode', res.data);
                setTimeout(() => {
                    wx.removeStorageSync('phoneCode');
                }, 3 * 60 * 1000);
                var interValObj = setInterval(function () {
                    if (that.data.countDown <= 0) {
                        that.setData({
                            countDown: 60,
                            getCodeDisabled: false
                        })
                        clearInterval(interValObj);
                    } else {
                        that.setData({
                            countDown: --that.data.countDown
                        })
                    }
                    console.log(that.data.countDown)
                }, 1000);
            } else {
                wx.showModal({
                    title: '发送失败',
                    content: res.msg,
                    showCancel: false
                })
                that.setData({
                    getCodeDisabled: false, 
                })
            }
        })
    },
    /*** 提交用户信息*/
    submitUserInfo(reg){
        let that = this;
        let name = reg.data.name;
        let phone = reg.data.phone;
        let phoneCode = wx.getStorageSync('phoneCode');
        console.log(reg.data.code)
        let warn;
        if (!name) {
            warn = "姓名不能为空";
        } else if (!phone) {
            warn = "号码不能为空";
        } else if (phone.trim().length != 11 || !/^1[3|4|5|6|7|8|9]\d{9}$/.test(phone)) {
            warn = "手机号格式不正确";
        }
        else if (!reg.data.code) {
            warn = "验证码不能为空";
        } else if (reg.data.code != phoneCode) {
            warn = "验证码不正确";
        }
        if (warn) {
            wx.showModal({
                title: '提示',
                content: warn,
                showCancel: false
            })
            return;
        }
        let url = '/user/user/regist';
        let param = {
            id: that.globalData.user.id,
            name: name,
            phone: phone,
            code: reg.data.code
        }
        that.post(url, param, res => {
            if (res.code == 0) {
                console.log(res)
                that.globalData.isBind = true;
                wx.setStorageSync('isBind', true);
                that.globalData.user.name = name;
                that.globalData.user.phone = phone;
                reg.setData({
                    showModal: true
                })

            } else {
                wx.showModal({
                    title: '提示',
                    content: res.msg,
                    showCancel: false
                })
            }
        })
    }
})